package org.vectrics.recruiter.struts.admin;

import java.text.SimpleDateFormat;
import java.util.Iterator;

import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.user.resume.email.EmailedResumeInfo;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.ContactInfo;
import org.vectrics.user.Person;
import org.vectrics.user.PersonMatch;
import org.vectrics.user.PersonMatchSet;
import org.vectrics.user.PersonName;
import org.vectrics.user.PersonNameList;
import org.vectrics.user.web.struts.UserSummaryTag;


public class EmailPersonMatchSelectTag extends VectricsTagSupport {

	private static final long serialVersionUID = -8145368146565198946L;
	
	private String emailedResumeId = null;

	public EmailPersonMatchSelectTag() {
		super();
	}

	protected String makeStartTag() {
		StringBuffer html = new StringBuffer();
		
		EmailedResumeInfo emailedResumeInfo = RecruitServiceLocator.getRecruitUserService().findEmailedResume(new Long(this.getEmailedResumeId()));
		Person person = emailedResumeInfo.getPerson();
		
		PersonMatchSet matchSet = (PersonMatchSet)this.getRequest().getAttribute("existingCandidates");
		if (matchSet == null) {
			throw new SystemException("Could not find request attribute 'existingCandidates'");
		}

		Table parsedDataTable = makeParsedDataTable(emailedResumeInfo);
		Row headerRow = parsedDataTable.addRow();
        headerRow.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");
		//headerRow.setDefaultCellClass("tableHdrBg");
        headerRow.setDefaultCellFontClass("tableHdrFont");
        headerRow.addCell().addText(this.getPhrase("prompt.found.names"));
        headerRow.addCell().addText(this.getPhrase("prompt.found.phone.numbers"));
        headerRow.addCell().addText(this.getPhrase("prompt.found.emails"));
		
		
		Row dataRow = parsedDataTable.addRow();
        dataRow.setDefaultCellFontClass("stdFont");
        Cell nameCell = dataRow.addCell();
        Cell phoneCell = dataRow.addCell();
        Cell emailCell = dataRow.addCell();
        
        PersonNameList nameList = matchSet.getNames();
        Iterator nameIter = nameList.iterator();
        String nameStr = "";
        while (nameIter.hasNext()) {
        	PersonName personName = (PersonName)nameIter.next();
        	String name = "";
        	if (personName.getFirstName() != null) {
        		name += personName.getFirstName();
        	}
        	if (personName.getMiddleName() != null) {
        		name += " " + personName.getMiddleName();
        	}
        	if (personName.getLastName() != null) {
        		name += " " + personName.getLastName();
        	}
        	nameStr += name + "<br>";
        }
        log.info("NameStr: " + nameStr);
    	nameCell.addElement(TextHelper.getFont("stdFont", nameStr));
        
        Iterator phoneIter = matchSet.getPhoneNumbers().iterator();
        while (phoneIter.hasNext()) {
        	String phoneNumber = (String)phoneIter.next();
        	phoneCell.addText(phoneNumber);
        	if (phoneIter.hasNext()) {
        		phoneCell.addText("<br>");
        	}
        }

        Iterator emailIter = matchSet.getEmailAddresses().iterator();
        while (emailIter.hasNext()) {
        	String email = (String)emailIter.next();
        	emailCell.addText(email);
        	if (emailIter.hasNext())
        		emailCell.addText("<br>");
        }
  
        
		Table table = new Table();
		table.setWidth("100%");
 
		makeSepLine(table);
		
		Row row = table.addRow();
		row.setDefaultCellFontClass("stdFont");
		Cell cellRadio = row.addCell();
		cellRadio.setWidth(0);
		cellRadio.setVAlign("top");
		Input input = new Input();
		input.setType(Input.RADIO);
		input.setName("personId");
		input.setChecked(true);
		input.setValue("0");
		cellRadio.addElement(input);

		Cell cellA = row.addCell();
		cellA.setWidth("50%");
		cellA.setColSpan(2);
		cellA.addText("None of these people match");
		
		Iterator iter = matchSet.iterator();
		while (iter.hasNext()) {
			PersonMatch personMatch = (PersonMatch)iter.next();
			makeSepLine(table);
			
			row = table.addRow();
			row.setDefaultCellFontClass("stdFont");
			cellRadio = row.addCell();
			cellRadio.setWidth(0);
			cellRadio.setVAlign("top");

			input = new Input();
			input.setType(Input.RADIO);
			input.setName("personId");
			input.setChecked(false);
			if (person != null) {
				if (personMatch.getPerson().getId().equals(person.getId())) {
					input.setChecked(true);
				}
			}
			input.setValue(personMatch.getPerson().getId().toString());
			cellRadio.addElement(input);

			cellA = row.addCell();
			cellA.setWidth("50%");
			cellA.setVAlign("top");

			Cell cellB = row.addCell();
			cellB.setWidth("50%");
			cellB.setVAlign("top");
			
			Table table1 = new Table();
			table1.setWidth("95%");
			cellA.addElement(table1);
			addNameValue(table1, "prompt.match.weight", personMatch.getScore().toString());
			addNameValue(table1, "prompt.person.name", personMatch.getPerson().getName());
			addNameValue(table1, "prompt.person.known.as.name", personMatch.getPerson().getKnownAs());
			addNameValue(table1, "prompt.email", personMatch.getPerson().createContactInfoIfNotExist().getEmail());

			Table table2 = new Table();
			table2.setWidth("95%");
			cellB.addElement(table2);
			
			SimpleDateFormat dateFormat = CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(this.getLocale());
			if (personMatch.getPerson().getDateOfBirth() != null) {
				addNameValue(table2, "prompt.person.birth.date", dateFormat.format(personMatch.getPerson().getDateOfBirth()));
			} else {
				addNameValue(table2, "prompt.person.birth.date", null);
			}
			ContactInfo contactInfo = personMatch.getPerson().createContactInfoIfNotExist();
			if ((contactInfo != null) && (contactInfo.getHomePhone() != null))
				addNameValue(table2, "prompt.home.phone", contactInfo.getHomePhone().toString());
			else 
				addNameValue(table2, "prompt.home.phone", null);
				
			if ((contactInfo != null) && (contactInfo.getWorkPhone() != null))
				addNameValue(table2, "prompt.work.phone", contactInfo.getWorkPhone().toString());
			else
				addNameValue(table2, "prompt.work.phone", null);

			if ((contactInfo != null) && (contactInfo.getHomeAddress() != null)) {
				String homeAddressLines = UserSummaryTag.makeAddressHtml(contactInfo.getHomeAddress());
				addNameValue(table2, "prompt.home.address", homeAddressLines);
			} else {
				addNameValue(table2, "prompt.home.address", null);
			}

		}
		makeSepLine(table);

		html.append(parsedDataTable.toString());
		html.append(table.toString());
		return html.toString();
	}

	
	private Table makeParsedDataTable(EmailedResumeInfo emailedResumeInfo) {
		Table table = new BorderTable();
		
		
		return(table);
	}
	
	
	private void makeSepLine(Table table) {
		Row row = table.addRow();
		Cell cell = row.addCell();
		cell.setColSpan(3);
		IMG sepLine = new IMG();
		sepLine.setWidth("100%");
		sepLine.setHeight(1);
		sepLine.setSrc(this.getRequest().getContextPath() + "/graphics/dk_slate_dot.gif");
		cell.addElement(sepLine);
	}
	
	
	private void addNameValue(Table table, String captionCode, String value) {
		Row row = table.addRow();
		row.setDefaultCellFontClass("stdFont");
		Cell captionCell = row.addCell();
		captionCell.setVAlign("top");
		String caption = this.getPhrase(captionCode);
		captionCell.addText(caption);

		Cell valueCell = row.addCell();
		valueCell.setVAlign("top");
		Table innerBorderTable = new BorderTable();
		innerBorderTable.setWidth("100%");
		Row innerBorderRow = innerBorderTable.addRow();
		Cell innerBorderCell = innerBorderRow.addCell();
		valueCell.addElement(innerBorderTable);
		innerBorderCell.setClass("readOnlyBg");
		if ((value == null) || (value.trim().length() == 0)) {
			innerBorderCell.addElement(TextHelper.getFont("stdFont", this.getPhrase("not.given")));
		} else {
			innerBorderCell.addElement(TextHelper.getFont("stdFont", value));
		}
	}

	/**
	 * @return Returns the emailedResumeId.
	 */
	public String getEmailedResumeId() {
		return emailedResumeId;
	}

	/**
	 * @param emailedResumeId The emailedResumeId to set.
	 */
	public void setEmailedResumeId(String emailedResumeId) {
		this.emailedResumeId = emailedResumeId;
	}

}
